<template>
  <el-dialog
    :model-value="visible"
    title="分配工单"
    width="500px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <div v-if="ticket" class="assign-content">
      <!-- 工单信息 -->
      <el-card class="ticket-info" shadow="never">
        <template #header>
          <h4>工单信息</h4>
        </template>
        <el-descriptions :column="1" size="small">
          <el-descriptions-item label="工单号">#{{ ticket.id }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ ticket.title }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">
            <el-tag :type="getStatusType(ticket.status)" size="small">
              {{ translateStatus(ticket.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityType(ticket.priority)" size="small">
              {{ translatePriority(ticket.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前负责人">
            {{ ticket.assigneeName || '未分配' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 分配表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分配给" prop="assigneeId">
          <el-select
            v-model="form.assigneeId"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
            @change="handleAssigneeChange"
          >
            <el-option
              v-for="agent in availableAgents"
              :key="agent.id"
              :label="agent.name"
              :value="agent.id"
            >
              <div class="agent-option">
                <span class="agent-name">{{ agent.name }}</span>
                <span class="agent-info">
                  {{ agent.role }} | 当前工单: {{ agent.ticketCount || 0 }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分配原因" prop="reason">
          <el-input
            v-model="form.reason"
            type="textarea"
            :rows="3"
            placeholder="请说明分配原因（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="优先级调整" prop="priority">
          <el-select v-model="form.priority" placeholder="保持原优先级" style="width: 100%">
            <el-option label="保持原优先级" value="" />
            <el-option label="高" value="HIGH" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="低" value="LOW" />
          </el-select>
        </el-form-item>

        <el-form-item label="预计完成时间" prop="dueDate">
          <el-date-picker
            v-model="form.dueDate"
            type="datetime"
            placeholder="选择预计完成时间"
            style="width: 100%"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="通知方式" prop="notifyMethods">
          <el-checkbox-group v-model="form.notifyMethods">
            <el-checkbox value="email">邮件通知</el-checkbox>
            <el-checkbox value="sms">短信通知</el-checkbox>
            <el-checkbox value="system">系统通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="添加备注" prop="note">
          <el-input
            v-model="form.note"
            type="textarea"
            :rows="2"
            placeholder="添加分配备注（可选）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <!-- 负责人信息 -->
      <el-card v-if="selectedAgent" class="agent-info" shadow="never">
        <template #header>
          <h4>负责人信息</h4>
        </template>
        <div class="agent-details">
          <div class="agent-avatar">
            <el-avatar :size="60" :src="selectedAgent.avatar">
              {{ selectedAgent.name?.charAt(0) }}
            </el-avatar>
          </div>
          <div class="agent-content">
            <div class="agent-name">{{ selectedAgent.name }}</div>
            <div class="agent-role">{{ translateRole(selectedAgent.role) }}</div>
            <div class="agent-stats">
              <div class="stat-item">
                <span class="stat-label">当前工单:</span>
                <span class="stat-value">{{ selectedAgent.ticketCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">完成率:</span>
                <span class="stat-value">{{ selectedAgent.completionRate || '0%' }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">平均处理时间:</span>
                <span class="stat-value">{{ selectedAgent.avgProcessTime || '-' }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '分配中...' : '确认分配' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { useTicketsStore } from '../store/tickets'
import { ElMessage } from 'element-plus'

export default {
  name: 'TicketAssignDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    ticket: {
      type: Object,
      default: null
    },
    agents: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const ticketsStore = useTicketsStore()
    const formRef = ref()
    const submitting = ref(false)

    // 表单数据
    const form = reactive({
      assigneeId: '',
      reason: '',
      priority: '',
      dueDate: '',
      notifyMethods: ['system'],
      note: ''
    })

    // 表单验证规则
    const rules = {
      assigneeId: [
        { required: true, message: '请选择负责人', trigger: 'change' }
      ]
    }

    // 可用负责人列表
    const availableAgents = computed(() => {
      return props.agents.map(agent => ({
        ...agent,
        ticketCount: getAgentTicketCount(agent.id),
        completionRate: getAgentCompletionRate(agent.id),
        avgProcessTime: getAgentAvgProcessTime(agent.id)
      }))
    })

    // 选中的负责人
    const selectedAgent = computed(() => {
      return availableAgents.value.find(agent => agent.id === form.assigneeId)
    })

    // 监听ticket变化，初始化表单
    watch(() => props.ticket, (newTicket) => {
      if (newTicket) {
        Object.assign(form, {
          assigneeId: newTicket.assigneeId || '',
          reason: '',
          priority: '',
          dueDate: newTicket.dueDate || '',
          notifyMethods: ['system'],
          note: ''
        })
      }
    }, { immediate: true })

    // 监听对话框显示状态，重置表单
    watch(() => props.visible, (visible) => {
      if (visible && props.ticket) {
        form.assigneeId = props.ticket.assigneeId || ''
        form.priority = ''
        form.reason = ''
        form.note = ''
        form.notifyMethods = ['system']
        formRef.value?.clearValidate()
      }
    })

    // 处理负责人变化
    const handleAssigneeChange = (assigneeId) => {
      // 可以在这里添加一些逻辑，比如自动设置预计完成时间
      if (assigneeId && !form.dueDate) {
        // 根据负责人工作量自动设置预计完成时间
        const agent = availableAgents.value.find(a => a.id === assigneeId)
        if (agent && agent.ticketCount > 5) {
          // 如果负责人工单较多，设置较晚的完成时间
          const dueDate = new Date()
          dueDate.setDate(dueDate.getDate() + 3)
          form.dueDate = dueDate.toISOString().slice(0, 19).replace('T', ' ')
        }
      }
    }

    // 获取负责人工单数量
    const getAgentTicketCount = (agentId) => {
      return ticketsStore.tickets.filter(t => t.assigneeId === agentId).length
    }

    // 获取负责人完成率
    const getAgentCompletionRate = (agentId) => {
      const agentTickets = ticketsStore.tickets.filter(t => t.assigneeId === agentId)
      if (agentTickets.length === 0) return '0%'
      
      const completedTickets = agentTickets.filter(t => t.status === 'RESOLVED' || t.status === 'CLOSED')
      const rate = Math.round((completedTickets.length / agentTickets.length) * 100)
      return `${rate}%`
    }

    // 获取负责人平均处理时间
    const getAgentAvgProcessTime = (agentId) => {
      const agentTickets = ticketsStore.tickets.filter(t => 
        t.assigneeId === agentId && 
        (t.status === 'RESOLVED' || t.status === 'CLOSED')
      )
      
      if (agentTickets.length === 0) return '-'
      
      const totalHours = agentTickets.reduce((sum, ticket) => {
        const created = new Date(ticket.createdAt)
        const resolved = new Date(ticket.updatedAt)
        const hours = (resolved - created) / (1000 * 60 * 60)
        return sum + hours
      }, 0)
      
      const avgHours = Math.round(totalHours / agentTickets.length)
      return `${avgHours}小时`
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        // 准备分配数据
        const assignData = {
          assigneeId: form.assigneeId,
          reason: form.reason,
          priority: form.priority || props.ticket.priority,
          dueDate: form.dueDate,
          notifyMethods: form.notifyMethods,
          note: form.note
        }

        // 调用分配API
        await ticketsStore.assignTicket(props.ticket.id, assignData)
        
        ElMessage.success('工单分配成功！')
        emit('success')
        emit('update:visible', false)
      } catch (error) {
        console.error('分配失败:', error)
        ElMessage.error('分配失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 取消操作
    const handleCancel = () => {
      emit('update:visible', false)
    }

    // 工具方法
    const getStatusType = (status) => {
      const types = {
        OPEN: 'warning',
        IN_PROGRESS: 'primary',
        PENDING: 'info',
        RESOLVED: 'success',
        CLOSED: 'info'
      }
      return types[status] || 'info'
    }

    const getPriorityType = (priority) => {
      const types = {
        HIGH: 'danger',
        MEDIUM: 'warning',
        LOW: 'info'
      }
      return types[priority] || 'info'
    }

    const translateStatus = (status) => {
      const statusMap = {
        OPEN: '待处理',
        IN_PROGRESS: '处理中',
        PENDING: '挂起',
        RESOLVED: '已解决',
        CLOSED: '已关闭'
      }
      return statusMap[status] || status
    }

    const translatePriority = (priority) => {
      const priorityMap = {
        HIGH: '高',
        MEDIUM: '中',
        LOW: '低'
      }
      return priorityMap[priority] || priority
    }

    const translateRole = (role) => {
      const roleMap = {
        admin: '管理员',
        agent: '客服',
        customer: '客户',
        manager: '经理'
      }
      return roleMap[role] || role
    }

    return {
      formRef,
      submitting,
      form,
      rules,
      availableAgents,
      selectedAgent,
      handleAssigneeChange,
      handleSubmit,
      handleCancel,
      getStatusType,
      getPriorityType,
      translateStatus,
      translatePriority,
      translateRole
    }
  }
}
</script>

<style scoped>
.assign-content {
  max-height: 70vh;
  overflow-y: auto;
}

.ticket-info,
.agent-info {
  margin-bottom: 20px;
}

.ticket-info h4,
.agent-info h4 {
  margin: 0;
  color: #303133;
}

.agent-option {
  display: flex;
  flex-direction: column;
}

.agent-name {
  font-weight: 500;
  color: #303133;
}

.agent-info {
  font-size: 12px;
  color: #909399;
}

.agent-details {
  display: flex;
  align-items: center;
  gap: 16px;
}

.agent-content {
  flex: 1;
}

.agent-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.agent-role {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.agent-stats {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.stat-label {
  color: #909399;
}

.stat-value {
  color: #303133;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .agent-details {
    flex-direction: column;
    text-align: center;
  }
  
  .agent-stats {
    align-items: center;
  }
  
  .stat-item {
    justify-content: center;
    gap: 8px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>
